package com.cmw.udp.l302;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/**
 * UDP 搜索者，用于搜索服务支持方
 */
public class UDPSearcher02 {
    private static final int LISTEN_PORT = 30000;

    public static void main(String[] args) throws IOException, InterruptedException {
        System.out.println("UDPSearcher02 Started.");

        //获取监听器
        Listener listener = listen();
        //发送广播
        sendBroadcast();

        //读取任意键盘信息后可以退出
        System.in.read();

        //打印设备信息
        List<Device> deviceList = listener.getDevicesAndClose();
        if(null == deviceList || deviceList.size() == 0){
            System.out.println("无法获取任何设备信息.");
            return;
        }
        deviceList.forEach((item)-> System.out.println(String.format("Device: %s",item.toString())));

        //完成
        System.out.println("UDPSearcher02 Finished.");
    }

    private static void sendBroadcast() throws IOException {
        System.out.println("UDPSearcher02 sendBroadcast started.");
        //作为搜索方，让系统自动分配端口
        DatagramSocket ds = new DatagramSocket();
        //构建一份请求数据
        String requestData = MessageCreator.buildWithPort(LISTEN_PORT);
        byte[] requestDataBytes = requestData.getBytes();
        DatagramPacket requestPack = new DatagramPacket(requestDataBytes, requestDataBytes.length);
        //20000端口，广播地址
        requestPack.setAddress(InetAddress.getByName("255.255.255.255"));
        requestPack.setPort(20000);
        ds.send(requestPack);
        ds.close();
        //完成
        System.out.println("UDPSearcher sendBroadcast finished.");
    }

    private static Listener listen() throws InterruptedException {
        System.out.println("UDPSearcher02 start listen.");
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Listener listener = new Listener(LISTEN_PORT, countDownLatch);
        listener.start();
        countDownLatch.await();
        return listener;
    }

    private static class Listener extends Thread{
        final int listenPort;
        final CountDownLatch countDownLatch;
        List<Device> devices = new ArrayList<>();
        boolean done = false;
        DatagramSocket ds = null;

        public Listener(int listenPort, CountDownLatch countDownLatch){
            super();
            this.listenPort = listenPort;
            this.countDownLatch = countDownLatch;
        }

        @Override
        public void run() {
            super.run();
            //通知已启动
            countDownLatch.countDown();

            try {
                ds = new DatagramSocket(listenPort);
                while (!done){
                    //构建接收实体
                    byte[] buf = new byte[512];
                    DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
                    //接收
                    ds.receive(receivePack);
                    //打印接收到的信息与发送者的信息
                    //发送者 IP,端口，数据
                    String ip = receivePack.getAddress().getHostAddress();
                    int port = receivePack.getPort();
                    byte[] dataArr = receivePack.getData();
                    int dataLen = receivePack.getLength();
                    String data = new String(dataArr);
                    System.out.println(String.format("UDPSearcher2 receive from ip:%s\t port:%d\t data:%s\t dataLen=%d",ip,port, data, dataLen));
                    //从数据中解析 sn 并添加到 devices 列表中

                    String sn = MessageCreator.parseSn(data);
                    if(null != sn){
                        Device device = new Device(port, ip, sn);
                        devices.add(device);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                close();
            }

        }

        private void close(){
            if(null == ds) return;
            ds.close();
            ds = null;
        }

        private List<Device> getDevicesAndClose(){
            done = true;
            close();
            return devices;
        }
    }

    private static class Device{
        final int port;
        final String ip;
        final String sn;

        public Device(int port, String ip, String sn) {
            this.port = port;
            this.ip = ip;
            this.sn = sn;
        }

        @Override
        public String toString() {
            return "Device{" +
                    "port=" + port +
                    ", ip='" + ip + '\'' +
                    ", sn='" + sn + '\'' +
                    '}';
        }
    }
}
